package com.lyl.security.module.login.service.impl;

import com.lyl.security.common.exception.BizException;
import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.module.login.model.dto.LoginDTO;
import com.lyl.security.module.login.service.LoginService;
import com.lyl.security.module.security.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * @author Mr.Luo
 * @date 2022-09-14 15:47
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final TokenService tokenService;

    @Override
    public String login(LoginDTO dto) {
        Authentication authenticate;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            if (e instanceof BadCredentialsException) {
                throw new BizException(ErrorCode.UNAUTHORIZED, "用户名密码不匹配");
            } else {
                throw new BizException(ErrorCode.UNAUTHORIZED, e.getMessage());
            }
        }
        return tokenService.setToken(authenticate);
    }
}
